from fastapi import APIRouter, Depends, HTTPException, status
from app.schemas import schemas
from sqlalchemy.orm import Session
from app.db.db import get_db
from app.models import models
from app.dependencies import get_current_user, get_current_active_user
from app.db import crud
from typing import List

router = APIRouter(tags=["account"])


# 添加账号信息
@router.post("/account", response_model=schemas.AccountInfo)
async def create_account(
    account: schemas.AccountCreate,
    db: Session = Depends(get_db),
    current_user: models.DUser = Depends(get_current_active_user),
):

    return crud.create_account(
        db, account, current_user.id
    )  # 这里没有显式的类型转换它也能自动转换


# 获取账号信息
@router.get("/accounts", response_model=List[schemas.AccountInfo])
async def get_accounts(
    db: Session = Depends(get_db),
    current_user: models.DUser = Depends(get_current_active_user),
):
    db_accounts = crud.get_accounts(db, current_user.id)

    return db_accounts


# 修改账号信息
@router.put("/account/{account_id}", response_model=schemas.AccountInfo)
async def update_account(
    account_id: int,
    account: schemas.AccountUpdate,
    db: Session = Depends(get_db),
    current_user: models.DUser = Depends(get_current_active_user),
):
    db_account = crud.update_account(db, account, current_user.id, account_id)

    if db_account is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Account not found"
        )

    return db_account


# 删除账号信息
@router.delete("/account/{account_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_account(
    account_id: int,
    db: Session = Depends(get_db),
    current_user: models.DUser = Depends(get_current_active_user),
):
    ret = crud.delete_account(db, current_user.id, account_id)
    if not ret:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Account not found"
        )
    return
